import re
import json

def extract_cookies_from_curl(curl_text):
    """从curl命令中提取Cookie"""
    # 查找-b参数后的Cookie字符串
    match = re.search(r'-b\s+\^"([^"]+)"', curl_text)
    if match:
        # 处理PowerShell转义字符
        cookie_str = match.group(1).replace('^%', '%')
        return cookie_str
    return None

def parse_cookies(cookie_str):
    """解析Cookie字符串为字典"""
    cookies = {}
    if not cookie_str:
        return cookies
    
    # 分割各个Cookie
    parts = cookie_str.split('; ')
    for part in parts:
        if '=' in part:
            key, value = part.split('=', 1)
            cookies[key] = value
    return cookies

def compare_cookies(cookie1, cookie2):
    """比较两个Cookie字典"""
    diff = {
        'only_in_1': {},
        'only_in_2': {},
        'different_values': {}
    }
    
    keys1 = set(cookie1.keys())
    keys2 = set(cookie2.keys())
    
    # 只在第一个Cookie中的键
    for key in keys1 - keys2:
        diff['only_in_1'][key] = cookie1[key]
    
    # 只在第二个Cookie中的键
    for key in keys2 - keys1:
        diff['only_in_2'][key] = cookie2[key]
    
    # 两个Cookie中都存在但值不同的键
    for key in keys1 & keys2:
        if cookie1[key] != cookie2[key]:
            diff['different_values'][key] = {
                'cookie1': cookie1[key],
                'cookie2': cookie2[key]
            }
    
    return diff

def main():
    # 读取文件内容
    with open('../docs/第一次发布文章请求.txt', 'r', encoding='utf-8') as f:
        first_request = f.read()
    
    with open('../docs/第二次发布文章请求.txt', 'r', encoding='utf-8') as f:
        second_request = f.read()
    
    # 从curl命令中提取Cookie
    first_cookie_str = extract_cookies_from_curl(first_request)
    second_cookie_str = extract_cookies_from_curl(second_request)
    
    # 解析Cookie
    first_cookies = parse_cookies(first_cookie_str)
    second_cookies = parse_cookies(second_cookie_str)
    
    # 读取config.json中的Cookie
    with open('../configs/config.json', 'r', encoding='utf-8') as f:
        config = json.load(f)
    config_cookie_str = config['cookie_string']
    config_cookies = parse_cookies(config_cookie_str)
    
    print("=" * 80)
    print("Cookie分析结果")
    print("=" * 80)
    
    print("\n第一次请求中的Cookie:")
    for key, value in first_cookies.items():
        print(f"  {key}: {value}")
    
    print("\n第二次请求中的Cookie:")
    for key, value in second_cookies.items():
        print(f"  {key}: {value}")
    
    print("\nconfig.json中的Cookie:")
    for key, value in config_cookies.items():
        print(f"  {key}: {value}")
    
    # 比较第一次和第二次请求的Cookie
    print("\n" + "=" * 80)
    print("第一次请求 vs 第二次请求 Cookie差异:")
    print("=" * 80)
    diff_1_2 = compare_cookies(first_cookies, second_cookies)
    
    if diff_1_2['only_in_1']:
        print("\n只在第一次请求中存在的Cookie:")
        for key, value in diff_1_2['only_in_1'].items():
            print(f"  {key}: {value}")
    
    if diff_1_2['only_in_2']:
        print("\n只在第二次请求中存在的Cookie:")
        for key, value in diff_1_2['only_in_2'].items():
            print(f"  {key}: {value}")
    
    if diff_1_2['different_values']:
        print("\n两次请求中值不同的Cookie:")
        for key, values in diff_1_2['different_values'].items():
            print(f"  {key}:")
            print(f"    第一次请求: {values['cookie1']}")
            print(f"    第二次请求: {values['cookie2']}")
    
    if not any(diff_1_2.values()):
        print("\n两次请求的Cookie完全相同")
    
    # 比较config.json和第一次请求的Cookie
    print("\n" + "=" * 80)
    print("config.json vs 第一次请求 Cookie差异:")
    print("=" * 80)
    diff_config_1 = compare_cookies(config_cookies, first_cookies)
    
    if diff_config_1['only_in_1']:
        print("\n只在config.json中存在的Cookie:")
        for key, value in diff_config_1['only_in_1'].items():
            print(f"  {key}: {value}")
    
    if diff_config_1['only_in_2']:
        print("\n只在第一次请求中存在的Cookie:")
        for key, value in diff_config_1['only_in_2'].items():
            print(f"  {key}: {value}")
    
    if diff_config_1['different_values']:
        print("\nconfig.json和第一次请求中值不同的Cookie:")
        for key, values in diff_config_1['different_values'].items():
            print(f"  {key}:")
            print(f"    config.json: {values['cookie1']}")
            print(f"    第一次请求: {values['cookie2']}")
    
    if not any(diff_config_1.values()):
        print("\nconfig.json和第一次请求的Cookie完全相同")
    
    # 检查WordPress安全相关的Cookie
    print("\n" + "=" * 80)
    print("WordPress安全Cookie分析:")
    print("=" * 80)
    
    security_cookies = ['wordpress_sec_', 'wordpress_logged_in_']
    for cookie_name in security_cookies:
        for key in first_cookies.keys():
            if key.startswith(cookie_name):
                print(f"\n{key}:")
                print(f"  第一次请求: {first_cookies[key]}")
                print(f"  第二次请求: {second_cookies.get(key, '不存在')}")
                print(f"  config.json: {config_cookies.get(key, '不存在')}")
                
                # 解析WordPress登录Cookie
                if key.startswith('wordpress_logged_in_'):
                    parts = first_cookies[key].split('|')
                    if len(parts) >= 4:
                        username, expiry, token, hash_val = parts[:4]
                        print(f"    用户名: {username}")
                        print(f"    过期时间戳: {expiry}")
                        try:
                            import datetime
                            expiry_date = datetime.datetime.fromtimestamp(int(expiry))
                            print(f"    过期日期: {expiry_date}")
                        except:
                            print(f"    过期日期: 无法解析")
                        print(f"    令牌: {token}")
                        print(f"    哈希: {hash_val[:20]}...")

if __name__ == "__main__":
    main()